package com.sweetest.luffy.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sweetest.luffy.entity.User;
import com.sweetest.luffy.page.Result;
import com.sweetest.luffy.service.IUserService;
import com.sweetest.luffy.util.CtxUtils;
import com.sweetest.luffy.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.security.auth.message.AuthException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {


    private ObjectMapper objectMapper = new ObjectMapper();

    @Resource
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try {
            String token = CtxUtils.getToken(request);

            if (StringUtils.isBlank(token)) {
                throw new AuthException("用户登录凭据为空");
            }
            Integer id = JwtUtil.getId(token);
            User user = userService.getById(id);

            if (null == user) {
                returnJson(request, response, Result.noauth("获取用户信息失败,请重新登陆！"));
                return false;
            }
    /*        if (user == null) {
                returnJson(request, response, Result.noauth("无用户信息,请重新登陆！"));
                return false;
            }
            String cacheToken = String.valueOf(redisUtil.get(Constants.PREFIX_USER_TOKEN + id));

            if (token.equals(cacheToken)) {//验证成功 刷新token
                // 设置超时时间
                redisUtil.expire(Constants.PREFIX_USER_TOKEN + id,  Constants.SESSION_TIME_OUT);
            } else {//没验证成功
                returnJson(request, response, Result.noauth("token未验证成功！"));
                return false;
            }*/

        } catch (AuthException e) {
            returnJson(request, response, Result.noauth("没有Token,请重新登陆！"));
            return false;
        } catch (Exception e) {
//            logger.error("验证用户登录时出错", e);
//            returnJson(request, response, new ResEnv<>(Constants.RES_CODE_UNAUTH, "验证用户登录时出错"));
//            return false;
        }
        return super.preHandle(request, response, handler);
    }

    public void returnJson(HttpServletRequest request, HttpServletResponse response, Object obj) throws IOException {
        if (obj == null)
            return;

        response.setContentType("application/json; charset=UTF-8");
        String json = objectMapper.writeValueAsString(obj);

        String callback = request.getParameter("callback");
        if (StringUtils.isNotBlank(callback)) {
            json = String.format("%s(%s)", callback, json);
        }

        response.getWriter().write(json);
    }
}
